package com.zzyl.intercept;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(Constants.USER_TOKEN);
        //如果token为空，则抛出异常
        if(ObjectUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //解析token,存放的用户登陆数据
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        String currentUser = (String) claims.get("currentUser");
        UserVo userVo = JSONUtil.toBean(currentUser, UserVo.class);
        //从redis中获取用户权限数据
        String s = redisTemplate.opsForValue().get("user:public_access_urls:" + userVo.getId());
        //将s转成集合
        List<String> urls = JSONUtil.toList(s, String.class);
        //判断当前请求的url是否在集合中
        //获取当前请求路径
        String requestURI = request.getRequestURI();
        //获取当前请求方式
        String method = request.getMethod();
        String url = method+requestURI;
        //遍历路径集合,如果匹配就放行
        for (String string : urls) {
            if(antPathMatcher.match(string, url)){
                //放行之前,将当前用户id存入本地线程
                UserThreadLocal.set(userVo.getId());
                return true;
            }
        }
        //如果没有匹配就抛出异常
        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       // 从本地线程中移除当前用户id
        UserThreadLocal.remove();
    }
}
